<template>
  <el-cascader
    class="select-area"
    :props="props"
    style="width: 100%"
    @change="change"
    v-model="prop.modelValue"
  />
</template>

<script setup lang="ts">
import type { CascaderProps, CascaderValue } from 'element-plus';

defineOptions({
  name: '',
});

interface IProps {
  modelValue: any;
}
const prop = withDefaults(defineProps<IProps>(), {
  modelValue: null,
});

const emit = defineEmits(['update:modelValue']);

const address = ref([
  { name: '', code: '', level: 0, mark: 'province', leaf: false, tag: '' }, // 省
  { name: '', code: '', level: 1, mark: 'citie', seniorcode: '', leaf: false, tag: 'provinceCode' }, // 市
  { name: '', code: '', level: 2, mark: 'area', seniorcode: '', leaf: true, tag: 'cityCode' }, // 区
]);
const props: CascaderProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    setTimeout(async () => {
      let item = address.value[level];
      const nodes: any =
        (await getArea({
          ...item,
          seniorcode: node.data?.code,
        })) || [];
      resolve(nodes);
    }, 200);
  },
};

const getArea = async (item: any) => {
  return new Promise((resolve, reject) => {
    import(`../../../public/area/${item.mark}s.json`).then((res: any) => {
      let arr = res.default,
        result: any = [];
      if (item.level === 0) {
        result = arr.map((ele: any) => ({
          value: ele.name,
          code: ele.code,
          label: ele.name,
          leaf: item.leaf,
          seniorcode: '',
        }));
      } else {
        result = arr
          .filter((obj: any) => item.seniorcode === obj[item.tag])
          .map((ele: any) => ({
            value: ele.name,
            code: ele.code,
            label: ele.name,
            leaf: item.leaf,
            seniorcode: item.seniorcode,
          }));
      }
      resolve(result);
    });
  });
};

const change = (value: CascaderValue) => {
  emit('update:modelValue', value);
};
</script>

<style lang="less" scoped>
.el-cascader-menu {
  max-width: 120px;
  width: 120px;
}
</style>
